package com.github.llyb120.sxmanage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.github.llyb120.sxmanage.UpdateServer.tempPath;
import static com.github.llyb120.sxmanage.Util.HandleScript;
import static com.github.llyb120.sxmanage.Util.RunScript;


/**
 * @Author: Administrator
 * @Date: 2020/12/15 15:17
 */
@Configuration
public class ServiceConfig {

//    public static ServiceConfig

//    @Value("${scripts}")
//    String scripts;

    private List<String> readNames(ClassPathResource resource){
        InputStream is = resource.getStream();
        List<String> list = new ArrayList<>();;
        IoUtil.readUtf8Lines(is, list);
        IoUtil.close(is);
        return list;
    }

    @Value("${script-path:}")
    String scriptPath;

    @Bean(name = "ms")
    public List<Config> configList() throws IOException {
        List<Config> list = new ArrayList<>();
        URL url = App.class.getResource("");
        String protocol = url.getProtocol();
        boolean runningInJar="jar".equals(protocol);

        File path;
        if(StrUtil.isNotBlank(scriptPath)){
            path = new File(scriptPath);
        } else if(runningInJar) {
            File tmp = new File(tempPath, IdUtil.objectId());
            tmp.mkdirs();
            tmp.deleteOnExit();
            String jarPath = JarTool.getJarPath();
            jarPath = jarPath.substring(jarPath.indexOf("file:") + 5, jarPath.indexOf("!"));
            System.out.println(String.format("unzip -d %s %s",tmp.getAbsolutePath(), jarPath));
            String finalJarPath = jarPath;
            RunScript(String.format("unzip -d %s %s", tmp.getAbsolutePath(), finalJarPath), false);
            path = new File(tmp.getAbsolutePath(), "BOOT-INF/classes/scripts");
        } else {
            path = new File(JarTool.getJarPath(), "scripts");
        }
        System.out.println(path.getAbsolutePath());
        System.out.println(path.listFiles());
            for (File serviceDir : path.listFiles()) {
                Config config = new Config();
                config.name = serviceDir.getName();//file.getName();
                for (File file : serviceDir.listFiles()) {
                    String realName = file.getName();
                    String scriptName = file.getName();
                    if (realName.endsWith(".sh")) {
                        scriptName = scriptName.substring(0, scriptName.length() - ".sh".length());
                    }
                    String cnt = HandleScript(FileUtil.readString(file, StandardCharsets.UTF_8));//, StandardCharsets.UTF_8));
                    if (scriptName.equals("health")) {
                        cnt = cnt.replaceAll("\r|\n", "");
                    }
                    try {
                        Field field = config.getClass().getDeclaredField(scriptName);
                        field.setAccessible(true);
                        field.set(config, cnt);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                list.add(config);
            }

        return list;
    }

    @Data
    public static class Config {
        String name;
        String start;
        String stop;
        String log;
        String restart;
        String health;
        String update;
//        List<String> update = new ArrayList<>();
    }
}
